// 登录与注册的模块
import {
  reqGetCode,
  reqRegister,
  reqUserLogin,
  reqUserInfo,
  reqUserLogout
} from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token'
const state = {
  // 验证码
  code: '',
  // token: localStorage.getItem('TOKEN')||'',
  // token: localStorage.getItem('TOKEN'),// 取不到就是null,null和''没区别
  token: getToken(),
  userInfo: {}
}
const mutations = {
  GETCODE: (state, code) => {
    state.code = code
  },
  GETTOKEN: (state, token) => {
    state.token = token
  },
  GETUSERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  clearLogout(state) {
    state.token = '' // vuex中的token
    state.userInfo = {}
    removeToken() // 本地存储中的token清空
  }
}
const actions = {
  // 获取验证码
  async getCode({ commit }, phone) {
    const result = await reqGetCode(phone)
    console.log('🚀 ~ file: index.js:7 ~ getCode ~ result:', result)
    if (result.code == 200) {
      commit('GETCODE', result.data)
    } else {
      return Promise.reject()
    }
  },
  // 用户注册
  async userRegister({ commit }, data) {
    const result = await reqRegister(data)
    console.log('🚀 ~ file: index.js:27 ~ userRegister ~ result:', result)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
  },
  // 登录业务:获取--【token】
  async userLogin({ commit }, data) {
    console.log('调用执行获取token')
    const result = await reqUserLogin(data)
    if (result.code == 200) {
      commit('GETTOKEN', result.data.token)
      // 持久化存储token
      // localStorage.setItem('TOKEN',result.data.token)
      setToken(result.data.token)
      return 'ok'
    } else {
      //登录失败
      return Promise.reject(new Error('faile'))
    }
  },
  // 获取用户信息
  async getUserInfo({ commit }) {
    let result = await reqUserInfo()
    if (result.code == 200) {
      commit('GETUSERINFO', result.data)
      return 'ok'
    } else {
      //登录失败
      return Promise.reject()
    }
  },
  // 退出登录
  async userLogout({ commit }) {
    // 向服务器发起一次请求，通知服务器清除token
    const result = await reqUserLogout()
    if (result.code == 200) {
      commit('clearLogout')
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
